#include"common.h"
#include"Epoll.h"

Epoll::Epoll():_epfd(-1),_events(nullptr)
{
    _epfd=epoll_create1(0);
    myAssert(_epfd!=-1,"epoll create error");
    _events=new epoll_event[MAX_EVENTS];
    printf("01\n");
    bzero(_events,sizeof(*_events)*MAX_EVENTS);
    printf("02\n");
}

std::vector<Channel*> Epoll::poll(int time_out)
{
    std::vector<Channel*> activeChannel;
    
    int nfds=epoll_wait(_epfd,_events,MAX_EVENTS,time_out);
    
    myAssert(nfds!=-1,"epoll_wait error");
    for(int i=0;i<nfds;i++)
    {
        Channel* newChannel=(Channel*)_events[i].data.ptr;
        newChannel->setRevents(_events[i].events);
        activeChannel.push_back(newChannel);
    }
    return activeChannel;
}
void Epoll::updateChannel(Channel* newChannel)
{
    struct epoll_event ev;
    bzero(&ev,sizeof(ev));
    //联合体，这里要初始化ptr
    ev.data.ptr=newChannel;
    ev.events=newChannel->getEvents();
    if(newChannel->getInEpoll())
    {
        myAssert(epoll_ctl(_epfd,EPOLL_CTL_MOD,newChannel->getFd(),&ev)!=-1,"channel update mod error");
    }
    else
    {
        newChannel->setInEpoll();
        myAssert(epoll_ctl(_epfd,EPOLL_CTL_ADD,newChannel->getFd(),&ev)!=-1,"channel update mod error");
    }
}

Epoll::~Epoll()
{
    if(_epfd!=-1)
    {
        close(_epfd);
        _epfd=-1;
    }
    delete[] _events;
} 

